package com.example.coursedesign.ui.home;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import com.example.coursedesign.R;

import java.lang.reflect.Field;

public class TimeUnitPickerBottomSheet extends BottomSheetDialogFragment {

    private static final String[] unitsLeft = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
    private static final String[] unitsRight = generateMinuteArray(); // 动态生成分钟数组
    // 动态生成 00 到 59 的分钟数组
    private static String[] generateMinuteArray() {
        String[] minutes = new String[60];
        for (int i = 0; i < 60; i++) {
            minutes[i] = String.format("%02d", i); // 确保是两位数格式，如 "01", "02", ..., "59"
        }
        return minutes;
    }

    private OnUnitsSelectedListener mListener;
    private int defaultUnitIndexLeft = 0; // 左边默认值
    private int defaultUnitIndexRight = 0; // 右边默认值

    public interface OnUnitsSelectedListener {
        void onTimeUnitSelected(String unitLeft, String unitRight);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.two_bottom_sheet_dosage_unit_picker, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        NumberPicker numberPickerLeft = view.findViewById(R.id.numberPicker_units1);
        NumberPicker numberPickerRight = view.findViewById(R.id.numberPicker_units2);
        Button confirmButton = view.findViewById(R.id.button_confirm1);
        Button cancelButton = view.findViewById(R.id.button_cancel1); // 假设你有一个取消按钮

        if (numberPickerLeft == null || numberPickerRight == null) {
            Log.e("TimeUnitPickerBottomSheet", "One or both NumberPickers are null");
            return;
        }

        setNumberPickerTextSize(numberPickerLeft, 26); // 设置左边 NumberPicker 的字体大小
        setNumberPickerTextSize(numberPickerRight, 26); // 设置右边 NumberPicker 的字体大小

        numberPickerLeft.setMinValue(0);
        numberPickerLeft.setMaxValue(unitsLeft.length - 1);
        numberPickerLeft.setDisplayedValues(unitsLeft);
        numberPickerLeft.setValue(defaultUnitIndexLeft); // 设置默认选择项
        numberPickerLeft.setWrapSelectorWheel(true);

        numberPickerRight.setMinValue(0);
        numberPickerRight.setMaxValue(unitsRight.length - 1);
        numberPickerRight.setDisplayedValues(unitsRight);
        numberPickerRight.setValue(defaultUnitIndexRight); // 设置默认选择项
        numberPickerRight.setWrapSelectorWheel(true);

        // 确保仅在点击“确定”按钮时触发回调
        confirmButton.setOnClickListener(v -> {
            if (mListener != null) {
                int selectedValueLeft = numberPickerLeft.getValue();
                int selectedValueRight = numberPickerRight.getValue();
                mListener.onTimeUnitSelected(unitsLeft[selectedValueLeft], unitsRight[selectedValueRight]);
            }
            dismiss();
        });

        // 取消按钮逻辑
        cancelButton.setOnClickListener(v -> dismiss());
    }

    // 设置 NumberPicker 文本大小的方法
    private void setNumberPickerTextSize(NumberPicker picker, float textSize) {
        try {
            Field[] pickerFields = NumberPicker.class.getDeclaredFields();
            for (Field pf : pickerFields) {
                if (pf.getName().equals("mSelectionDivider")) {
                    continue;
                }
                if (pf.getName().equals("mInputText")) {
                    pf.setAccessible(true);
                    EditText inputText = (EditText) pf.get(picker);
                    if (inputText != null) {
                        inputText.setTextSize(textSize);
                    }
                    break;
                }
            }
        } catch (Exception e) {
            Log.e("TimeUnitPickerBottomSheet", "Failed to set text size for NumberPicker: " + e.getMessage());
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        // 检查是否实现了接口
        if (context instanceof OnUnitsSelectedListener) {
            mListener = (OnUnitsSelectedListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnUnitsSelectedListener");
        }

        // 从 Bundle 中获取传递的参数
        if (getArguments() != null) {
            defaultUnitIndexLeft = getArguments().getInt("defaultUnitIndexLeft", 0);
            defaultUnitIndexRight = getArguments().getInt("defaultUnitIndexRight", 0);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);
    }
}